<?php

/**

 * @Author: kendy

 * @Date:   2019-11-26 10:32:59

 * @Last Modified by:   jiayanting

 * @Last Modified time: 2020-04-27 15:06:35

 */ 

namespace app\api\controller;

use think\queue\Job;
use think\Db;

use think\Request;  

use app\common\model\FriendsCircleModel as fc;

use app\common\model\OrderRefund as orf;

use app\api\model\Payments as p;

use think\loader;


use app\api\model\OrderRefund as ore;

use think\Queue;

class Test extends Nocommon

{

    public function payment()
    {

            $MaxCancelCode = Db::name("jlou_order")
                        ->where('goods_id', 23)
                        ->order('order_id desc')
                        ->limit(1)
                        ->find(); 
                  
               if (!empty($MaxCancelCode['cancel_code'])){ $code =  (int)substr($MaxCancelCode['cancel_code'],4,11);  $data['cancel_code'] = 'YSLY'.($code + 1); }
               else{ $data['cancel_code']  = 'YSLY1000000';}
               print_r($data);return;

        $orf = new orf();

        $obj['trade_no'] = 2020030910248989;// $obj["trade_no"]; //支付宝交易号

        $obj['order_price'] = 10649874968497;//$obj["out_trade_no"]; //商户订单号

        $obj['total_amount'] = 0.01;//(int)$obj["user_id"];

        $obj['order_sn'] = 5;//订单类型 订单类型 1酒店，2景点，3跟团

        $obj['pay_type'] = 2;//(int)$obj["pay_type"]; //支付类型1支付宝，2微信

        $obj['uid'] = 2;//(float)$obj["total_amount"];
        $obj['refund_reason'] = 2;

        $orf->weixinRefund($obj);

        //微信支付

//       Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

//       $config = new \WxPayConfig();

//       $WxPay  = new \WxPayApi();

//       $WxData = new \WxPayRefund();

//

//       $dataArr = array(

//

//           'appid' => $config->GetAppId(),

//           'mch_id' => $config->GetMerchantId(),

//           'nonce_str' => $WxPay->getNonceStr(),

//           'total_fee' => 0.01*100,    //订单金额  单位 转为分

//           'refund_fee' => 0.01*100,    //退款金额 单位 转为分

//           'out_trade_no'=>'2020022410199995',    //商户订单号

//           'out_refund_no'=>'2020022410113456',    //商户退款单号

//           'refund_desc'=>'商品已售完',   //退款原因（选填）

//       );

//

//       $WxData->SetAppid($dataArr['appid']);

//       $WxData->SetMch_id($dataArr['mch_id']);

//       $WxData->SetNonce_str($dataArr['nonce_str']);

//       $WxData->SetTotal_fee($dataArr['total_fee']);

//       $WxData->SetOut_trade_no($dataArr['out_trade_no']);

//       $WxData->SetOut_refund_no($dataArr['out_refund_no']);

//       $WxData->SetRefund_fee($dataArr['refund_fee']);

//       $WxData->SetOp_user_id($dataArr['mch_id']);

//       $WxData->SetSign($config);

//       $return = $WxPay->refund($config,$WxData);

//       var_dump($return);


//        $p = new p();

//      /*  $obj['trade_no'] = 10214587456;// $obj["trade_no"]; //支付宝交易号

//        $obj['out_trade_no']=121;//$obj["out_trade_no"]; //商户订单号

//        $obj['uid']=2;//(int)$obj["user_id"];

//        $obj['pay_type']=2;//(int)$obj["pay_type"]; //支付类型1支付宝，2微信

//        $obj['pay_price']=0.01;//(float)$obj["total_amount"];

//        $obj['order_type']=2;//订单类型 订单类型 1酒店，2景点，3跟团*/

//          $obj['trade_no'] = 2020011057504912; //在线支付交易流水

//         $obj['out_trade_no'] = 2020022410199990; //商户订单号

//         $obj['total_amount'] = 0.01;//支付的金额

//         $obj['order_type'] = 1;//订单类型 订单类型 1酒店，2景点，3跟团

//          $obj['pay_type'] = 2;//支付类型1支付宝，2微信

//        $obj['uid'] = 2;

//        $p->complatePay($obj);


    }


    public function bbaa(){
        
        //定时删除操作日志 定时删除一个月之前的
        $result = Db::name('log_operates')
        ->where(['operate_time'=>['lt',time()]])
        ->select();


         echo "<pre>";
         print_r($result);
    }

    public function testabs()
    {
        echo time();

        //退款成功业务逻辑
        $hotelOrder = Db::name('hotel_order')
            ->where('order_sn', "2020032357515198")
            ->find();
        if (!empty($hotelOrder)) {
            $obj['order_sn'] = $hotelOrder['order_sn'];
            $obj['refund_trade_no'] = 123;
            $obj['object_id'] = 123;
            $obj['object_type'] = 4;
            $obj['user_id'] = 15;
            $obj['refund_status'] = 1;
            $obj['refund_reason'] = "自动退款";
            $obj['order_price'] = 4566 / 100;
            $orderRefund = new ore();
            $orderRefund->addOrderRefund($obj);
            //新增订单日志
            $logOrder = [];
            $logOrder['order_id'] = $hotelOrder['order_id'];
            $logOrder['order_status'] = 4;
            $logOrder['log_content'] = "订单已退款";
            $logOrder['user_id'] = $hotelOrder['uid'];
            $logOrder['create_time'] = time();
            $logOrder['order_type'] = 4;
            Db::name('log_orders')->insert($logOrder);
            //创建一条支付流水记录
            $lm = [];
            $lm['target_type'] = 0;
            $lm['target_id'] = $hotelOrder['uid'];
            $lm['data_id'] = 1;
            $lm['data_src'] = 1;
            $lm['remark'] = '订单【' . $hotelOrder['order_sn'] . '】退款￥' . $hotelOrder['order_price'];
            $lm['money_type'] = 0;
            $lm['money'] = $hotelOrder['order_price'];
            $lm['pay_type'] = $hotelOrder['pay_type'];
            $lm['create_time'] = date('Y-m-d H:i:s');
            Db::name('log_moneys')->insert($lm);

        }

    }

    public function complatePay()

    {

        $orf = new orf();

        $result = Db::name('bargain_order')
            ->field("order_price,order_sn,order_id,uid,pay_type")
            ->where('order_id', 21)
            ->find();

        $result['refund_desc'] = "ceshi";

        $rs = $orf->weixinRefund($result);

        print_r($rs);

    }

    public function abs()
    {
        phpinfo();
    }


    /*public function fire(){
               $isJobStillNeedToBeDone=$this->checkDatabaseToSeeIfJobNeedToBeDone($data);

              if(!$isJobStillNeedToBeDone){

                  $job->delete();

                  return;

              }

            

              $isJobDone = $this->doHelloJob($data);



              if ($isJobDone) {

                  //如果任务执行成功， 记得删除任务

                  $job->delete();

                  print("<info>Hello Job has been done and deleted"."</info>\n");

              }else{

                  if ($job->attempts() > 3) {

                      //通过这个方法可以检查这个任务已经重试了几次了

                      print("<warn>Hello Job has been retried more than 3 times!"."</warn>\n");

                    $job->delete();

                      // 也可以重新发布这个任务

                      //print("<info>Hello Job will be availabe again after 2s."."</info>\n");

                      //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行

                  }

              }

          }*/

    public function doHotelOrderJob()
    {

    }


    public function doHelloJob()
    {
        $data['order_id'] = 93;
        //根据消息中的数据进行实际的业务处理
        //查看该订单的状态是否为待确认，
        $hotelOrder = Db::name('hotel_order')
            ->where(['order_id' => $data['order_id'], 'order_status' => 6])
            ->find();
        if (!empty($hotelOrder)) {
            Db::startTrans();
            try {
                $send = [
                    '1' => $hotelOrder['linkman'],
                    '2' => $hotelOrder['order_sn']
                ];
                $data['order_status'] = 5;
                $data['cancel_id'] = 2;
                $orf = new orf();
                $obj['order_sn'] = $hotelOrder['order_sn'];
                $obj['object_id'] = $hotelOrder['hotel_id'];
                $obj['object_type'] = 4;
                $obj['user_id'] = $hotelOrder['uid'];
                $obj['refund_status'] = 1;
                $obj['refund_reason'] = "商户未确认自动退款";
                $obj['order_price'] = $hotelOrder['order_price'];
                //退款
                //查看支付类型
                $hotelOrder['refund_reason'] = "商户未确认自动退款";
                $payType = $hotelOrder['pay_type'];//1支付宝 2微信
                if ($payType == 1) {
                    //$rs = $orf->aliRefund($hotelOrder);
                }
                if ($payType == 2) {
                    //$rs = $orf->weixinRefund($hotelOrder);
                }

                //if($rs == 'SUCCESS'){
                Db::name('hotel')
                    ->where('hotel_id', $hotelOrder['hotel_id'])
                    ->setDec('sum_sale', 1);
                Db::name('hotel_order')
                    ->where('order_id', $hotelOrder['order_id'])
                    ->update($data);
                $orderRefund = new ore();
                $orderRefund->addOrderRefund($obj);
                // }else{
                //    return false;
                //  }

                //给用户发送短信
                sendJsmsMessage($hotelOrder['tel'], 174984, $send);
                Db::commit();
                return 1;
            } catch (\Exception $e) {
                Db::rollback();
                print_r($e->getMessage());
                return 1;
            }
        }

        return 0;
    }

    public function testCron()
    {


        $jobHandlerClassName = 'app\api\job\Order';

        $jobQueueName = 'Hello';

        $jobData = [

            'uid' => 2,

            'order_id' => 93,

        ];


        $isPushed = Queue::later(10, $jobHandlerClassName, $jobData, $jobQueueName);

        if ($isPushed !== false) {

            echo '成功';

        } else {

            echo '失败';

        }


    }


    public function index()

    {

        $p = new p();

    }


    public function codes()

    {


        $order_id = 1;

        $redirect_url = urlencode('http://' . $_SERVER['SERVER_NAME'] . '/codes?goods_id=' . $order_id);

        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=" . $redirect_url . "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

        $errorCorrectionLevel = 'H';//容错级别

        $matrixPointSize = 3;//图片大小慢慢自己调整，只要是int就行

        $path = 'uploads/';  //上传位置

        if (!file_exists($path)) {

            mkdir($path, 0777, true);

        }

        $QR = $QRB = $path . rand(10000, 99999) . time() . ".png";

        vendor('phpqrcode.phpqrcode');//引入插件类

        \QRcode::png($url, $QR, $errorCorrectionLevel, $matrixPointSize, 2);

        //注意前面的反斜杠，因为插件中的类是没有命名空间的，要在前面加一个反斜杠

        return $QR;

    }


    public function zuse()

    {


        $uids = array(1, 2, 3, 4, 5, 6);


        $sockets = array();


        foreach ($uids as $uid) {

            if (!$socket = stream_socket_client("127.0.0.1:80", $errno, $errstr)) {

                echo "$errstr\n";

                continue;

            }

            //根据自己的协议向服务端写入数据，这里模拟HTTP协议

            fwrite($socket, "GET / HTTP/1.1\r\nHost:www.baidu.com\r\n\r\n");

            //设置成非堵塞

            stream_set_blocking($socket, 0);


            //记录数组

            $sockets[(int)$socket] = $socket;

        }


        //批量等待数据返回

        while (count($sockets) > 0) {

            $read = $sockets;

            $wirte = $e = array();

            //等待数据可读

            if (stream_select($read, $write, $e, 10)) {

                //循环读数据

                echo fread($socket, 81912);

                fclose($socket);

                unset($sockets[(int)$socket]);


            }


        }


    }


    public function buchongfu()

    {

        echo getRandNumber(0, 9, 8);

    }


    public function sendMess()

    {

        $send = [

            '1' => '沂水地下大峡谷',

            '2' => '门票',

            '3' => '3点'

        ];

        $res = sendJsmsMessage(3, 174985, $send);//$user_id,$temp_id,$temp_para,$time = null,$sign_id = null

        print_r($res);

    }


    public function redisOp()
    {

        $redis = new  Redis();

        $redis->connect('114.67.109.129', 6379);

        $count = $redis->exists('count') ? $redis->get('count') : 1;

        echo $count;

        $redis->set('count', ++$count);

    }


    public function alipayRefund()
    {

        Loader::import('.alipay.aop.AopClient');

        Loader::import('.alipay.aop.request.AlipayTradeRefundRequest');

        $aop = new \AopClient ();

        $aop->gatewayUrl = config('alipay')['gatewayUrl'];

        $aop->appId = config('alipay')['appId'];

        $aop->rsaPrivateKey = config('alipay')['rsaPrivateKey'];

        $aop->alipayrsaPublicKey = config('alipay')['alipayrsaPublicKey'];

        $aop->apiVersion = '1.0';

        $aop->signType = config('alipay')['signType'];

        $aop->postCharset = 'UTF-8';

        $aop->format = config('alipay')['format'];


        $request = new \AlipayTradeRefundRequest();


        $bizcontent = json_encode(['out_trade_no' => '2020022498579756', 'refund_amount' => 0.01, 'refund_reason' => '正常退款']);

        $request->setBizContent($bizcontent);

        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

        $resultCode = $result->$responseNode->code;

        return $resultCode;


    }

    public function tst()
    {
        $jobHandlerClassName = 'app\api\job\Test';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName = "test";
        // 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
        //   ( jobData 为对象时，需要在先在此处手动序列化，否则只存储其public属性的键值对)
        $jobData = [
            'uid' => 1,

        ];
        // 4.将该任务推送到消息队列，等待对应的消费者去执行
        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
        if ($isPushed !== false) {
            echo '成功';

        } else {
            echo '失败';

        }
    }


    public function tttt()
    {
        $s1 = 20.00 * 100;
        $s2 = 0.00 * 100;
        $s3 = 19.99 * 100;
        $s4 = bcsub($s1, $s3, 2) / 100;
        $s5 = ($s1 - $s3) / 100;
        var_dump($s4);
        var_dump($s5);
        echo $s4;
    }

    public function user()
    {
        $data = [];

        for($i=0;$i<200;$i++){
            $res = $this->getRequest('https://api.uomg.com/api/rand.avatar?format=json');
            $data[] = [
                'phone'=>rand(),
                'password'=>rand(),
                'nickname'=>randomkeys(8),
                'user_icon'=>$res,
                'sex'=>0,
                'token'=>'',
                'create_time'=>date('Y-m-d H:i:s'),
                'is_del'=>0,
                'is_real'=>0
            ];
        }
       $res =  Db::name('user')->insertAll($data);
        if($res){
            return '成功';
        }
    }

    public function get()
    {


              var_dump(Db::name('user')->field('uid')->orderRaw('rand()')->limit(1)->find());

    }

    function getRequest($url){
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        //将返回的json对象解码成数组对象并返回
        $output = json_decode($output,true);
        return $output['imgurl'];
    }
	

}